package com.ruoyi.web.controller.admin.newSystem;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.PageResult;
import com.ruoyi.common.core.domain.entity.AdminUserDO;
import com.ruoyi.common.core.domain.entity.DeptDO;
import com.ruoyi.common.core.domain.entity.RoleDO;
import com.ruoyi.common.enums.CommonStatusEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.newSystem.bean.input.UserPageReqVO;
import com.ruoyi.newSystem.bean.input.UserUpdateReqVO;
import com.ruoyi.newSystem.bean.output.UserPageItemRespVO;
import com.ruoyi.newSystem.service.AdminUserService;
import com.ruoyi.newSystem.service.DeptService;
import com.ruoyi.newSystem.service.PermissionService;
import com.ruoyi.newSystem.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import static com.ruoyi.common.core.domain.AjaxResult.success;
import static com.ruoyi.common.utils.collection.CollectionUtils.convertList;

/**
 * The type User controller.
 */
@Slf4j
@Tag(name = "管理后台 - 用户")
@RestController
@RequestMapping("/newSystem/user")
@Validated
public class UserController {

    @Resource
    private AdminUserService userService;
    @Resource
    private DeptService deptService;

    @Resource
    private PermissionService permissionService;
    @Resource
    private RoleService roleService;


    /**
     * Update user common result.
     *
     * @param reqVO the req vo
     * @return the common result
     */
    @PutMapping("/update")
    @Operation(summary = "修改用户")
    public AjaxResult update(@Valid @RequestBody UserUpdateReqVO reqVO) {
        userService.updateUser(reqVO);
        return success(true);
    }


    /**
     * 添加用户
     *
     * @param adminUserDO 用户信息
     * @return ajax
     * @throws Exception 未填写异常
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody AdminUserDO adminUserDO) throws Exception {
        //如果密码为空就给默认密码
        if (StringUtils.isBlank(adminUserDO.getPassword())) {
            adminUserDO.setPassword("123456");
        }
        String s = Md5Utils.hash(adminUserDO.getPassword());
        AdminUserDO adminUserDO1 = new AdminUserDO();
        adminUserDO1.setPassword(s);
        adminUserDO1.setUsername(adminUserDO.getUsername());
        adminUserDO1.setNickname(adminUserDO.getNickname());
        //创建用户的时候给初始密码时间
        adminUserDO1.setPasswordTime(DateUtils.getTime());
        userService.createUser(adminUserDO1);
        return success();
    }


    /**
     * 修改用户密码
     *
     * @return the common result
     */
    @PostMapping("/update-password")
    public AjaxResult updateUserPassword(@RequestBody Password password) {
        userService.updateUserPassword(password.getId(),
                Md5Utils.hash(password.getOldPassword()),
                Md5Utils.hash(password.getNewPassword()));
        return success(true);
    }

    /**
     * Update user status common result.
     *
     * @param reqVO the req vo
     * @return the common result
     */
    @PutMapping("/updateStatus")
    public AjaxResult updateStatus(@Valid @RequestBody AdminUserDO reqVO) {
        userService.updateUserStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    /**
     * Gets user page.
     *
     * @param reqVO the req vo
     * @return the user page
     */
    @GetMapping("/getUserPage")
    public AjaxResult getUserPage(@Valid UserPageReqVO reqVO) {
        // 获得用户分页列表
        PageResult<AdminUserDO> pageResult = userService.getUserPage(reqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal())); // 返回空
        }

        // 获得拼接需要的数据
        Collection<Long> deptIds = convertList(pageResult.getList(), AdminUserDO::getDeptId);
        List<DeptDO> deptList = deptService.getDeptList(deptIds);
        // 拼接结果返回
        List<UserPageItemRespVO> userList = new ArrayList<>(pageResult.getList().size());
        pageResult.getList().forEach(user -> {
            UserPageItemRespVO respVO = new UserPageItemRespVO();
            BeanUtils.copyProperties(user, respVO);
//            respVO.setDept(deptList.get(user.getDeptId()));
            userList.add(respVO);
        });
        return success(new PageResult<>(userList, pageResult.getTotal()));
    }

    /**
     * 获取用户精简信息列表
     *
     * @return simple user list
     * @description 只包含被开启的用户 ，主要用于前端的下拉选项
     */
//    @GetMapping("/list-all-simple")
//    @SystemCheckPermission(value = "system:user:list")
//    @TLogAspectExt(str = "修改用户状态", moduleName = "admin-user", type = OperateTypeEnum.UPDATE, convert = SystemTLogConvert.class)
//    public CommonResult<List<UserSimpleRespVO>> getSimpleUserList() {
//        // 获用户列表，只要开启状态的
//        List<AdminUserDO> list = userService.getUserListByStatus(CommonStatusEnum.ENABLE.getStatus());
//        // 排序后，返回给前端
//        return success(mapperFacade.mapAsList(list, UserSimpleRespVO.class));
//    }

    /**
     * Gets user.
     *
     * @param id the id
     * @return the user
     */
    @GetMapping("/getUser")
    public AjaxResult getUser(@RequestParam("id") Long id) {
        AdminUserDO user = userService.getUserByUserId(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        Set<Long> roleIds = permissionService.getUserRoleIdListByUserId(id);
        List<RoleDO> roles = roleService.getRoleList(roleIds);
        roles.removeIf(role -> !CommonStatusEnum.ENABLE.getStatus().equals(role.getStatus())); // 移除禁用的角色

        if (CollectionUtil.isEmpty(roles)) {
            roles = new ArrayList<>();
        }
        Set<Long> deptIds = permissionService.getUserRoleIdListByUserId(id);
        List<DeptDO> depts = deptService.getDeptList(deptIds);
        depts.removeIf(dept -> !CommonStatusEnum.ENABLE.getStatus().equals(dept.getStatus())); // 移除禁用的部门

        if (CollectionUtil.isEmpty(roles)) {
            depts = new ArrayList<>();
        }
        UserPageItemRespVO convert = new UserPageItemRespVO();
        BeanUtils.copyProperties(user, convert);

        convert.setRoleIds(CollectionUtils.convertSet(roles, RoleDO::getId));
        convert.setRoleList(roles);

        convert.setDeptIds(CollectionUtils.convertSet(depts, DeptDO::getId));
        convert.setDeptList(depts);
        return success(convert);
    }

    /**
     * Export user list.
     *
     * @param reqVO    the req vo
     * @param response the response
     * @throws IOException the io exception
     */
//    @GetMapping("/export")
//    @SystemCheckPermission(value = "system:user:export")
//    @TLogAspectExt(str = "导出用户", moduleName = "admin-user", type = EXPORT)
//    public void exportUserList(@Validated UserExportReqVO reqVO,
//                               HttpServletResponse response) throws IOException {
//        // 获得用户列表
//        List<AdminUserDO> users = userService.getUserList(reqVO);
//
//        // 获得拼接需要的数据
//        Collection<Long> deptIds = convertList(users, AdminUserDO::getDeptId);
//        Map<Long, DeptDO> deptMap = deptService.getDeptMap(deptIds);
//        Map<Long, AdminUserDO> deptLeaderUserMap = userService.getUserMap(
//                convertSet(deptMap.values(), DeptDO::getLeaderUserId));
//        // 拼接数据
//        List<UserExcelVO> excelUsers = new ArrayList<>(users.size());
//        users.forEach(user -> {
//            UserExcelVO excelVO = UserConvert.INSTANCE.convert02(user);
//            // 设置部门
//            MapUtils.findAndThen(deptMap, user.getDeptId(), dept -> {
//                excelVO.setDeptName(dept.getName());
//                // 设置部门负责人的名字
//                MapUtils.findAndThen(deptLeaderUserMap, dept.getLeaderUserId(),
//                        deptLeaderUser -> excelVO.setDeptLeaderNickname(deptLeaderUser.getNickname()));
//            });
//            excelUsers.add(excelVO);
//        });
//
//        // 输出
//        ExcelUtils.write(response, "用户数据.xls", "用户列表", UserExcelVO.class, excelUsers);
//    }

    /**
     * Import template.
     *
     * @param response the response
     * @throws IOException the io exception
     */
//    @GetMapping("/get-import-template")
//    @Operation(summary = "获得导入用户模板")
//    public void importTemplate(HttpServletResponse response) throws IOException {
//        // 手动创建导出 demo
//        List<UserImportExcelVO> list = Arrays.asList(
//                UserImportExcelVO.builder().username("test001").deptId(1L).email("123456@google.cn").mobile("15512344321")
//                        .nickname("后台").status(CommonStatusEnum.ENABLE.getStatus()).sex(SexEnum.MALE.getSex()).build(),
//                UserImportExcelVO.builder().username("test001").deptId(2L).email("123456@google.cn").mobile("15512344321")
//                        .nickname("后台").status(CommonStatusEnum.DISABLE.getStatus()).sex(SexEnum.FEMALE.getSex()).build()
//        );
//
//        // 输出
//        ExcelUtils.write(response, "用户导入模板.xls", "用户列表", UserImportExcelVO.class, list);
//    }

    /**
     * Import excel common result.
     *
     * @param file          the file
     * @param updateSupport the update support
     * @return the common result
     * @throws Exception the exception
     */
//    @PostMapping("/import")
//    @Operation(summary = "导入用户")
//    @Parameters({
//            @Parameter(name = "file", description = "Excel 文件", required = true),
//            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
//    })
//    @SystemCheckPermission(value = "system:user:import")
//    public CommonResult<UserImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
//                                                      @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
//        List<UserImportExcelVO> list = ExcelUtils.read(file, UserImportExcelVO.class);
//        return success(userService.importUserList(list, updateSupport));
//    }


}

@Data
class Password {
    private Long id;
    private String oldPassword;
    private String newPassword;
}
